//
//  CommodityViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/20.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyJSON
import MJRefresh

class CommodityViewController: UIViewController,FYSliderViewCustomizable,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {

    var sliderView:FYSliderView!
    
    var idStr : String = ""
    var productImgView : String = ""
    var isShoppingCar = ""
    
    
    let COMMODITYCELL = "CommodityTableViewCell"
    let SHARECELL = "ShareCell"
    let DETAILCELL = "DetailCell"
    
//    var mainScrollView: SSCycleScrollView?
    var products_options_id = ""
    
    
//  放大缩小的item数组
    var itemsArray = NSMutableArray()
    
    var dataDic = NSDictionary()
    var imageDataArray = NSMutableArray(capacity: 0)
    var attributeArray = NSMutableArray(capacity: 0)
    
    var sizeView = UIView()
    
    
    let titleArray = ["PRODUCT INFO",
                      "REVIEWS",
                      "ADD TO WISHLIST"]
    let imageArray = ["icon_info",
                      "icon_reviews",
                      "icon_add"]
    
    
    
    
    var myTableView = UITableView(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-64-SCREEN_HEIGHT*0.08), style: .grouped)
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        

        self.title = "Details"
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.getData()
        self.creatNavView()
        self.creatTabeleView()
        self.creatAddToCartView()
        
    
    }
    //MARK: - FYSliderView配置信息
    var controlType: FYPageControlType{
        return .custom(currentColor:UIColor.red , normalColor:UIColor.black,layout:[.point(x:.centerX, y:.bottom(13))])
    }
    
    deinit{
        print("CommodityViewController")
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        sideMenuViewController()?.menuContainerView?.allowPanGesture = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}


extension CommodityViewController{
    fileprivate func getData(){
        
        
        let parma = ["main_page":"product_info","products_id":self.idStr]
        NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                let dic = result!["data"]as?NSDictionary
                self.dataDic = dic!
                
                let array = dic!["addtional_images"] as? [[String:NSObject]]
                for dic in array!{
                    self.imageDataArray.add(dic)
                }
                
                let attributeData = dic!["products_attrbutes"]as?[[String:NSObject]]
                for dictionary in attributeData!{
                    self.products_options_id = (dictionary["products_options_id"]as?String)!
                    let attArr = dictionary["products_options_values"]as?[[String : NSObject]]
                    for diccc in attArr!{
                        self.attributeArray.add((diccc as? NSDictionary)!)
                    }
                }
                
                
                SVProgressHUD.showSuccess(withStatus: "Load successfully!")
                self.myTableView.mj_header.endRefreshing()
                self.myTableView.reloadData()
                
            }else{
                SVProgressHUD.showError(withStatus: "Commodity info error:" + String(describing: error))
                print("Commodity info error:" + String(describing: error))
            }
        }
        
        
    }
}

extension CommodityViewController{
    fileprivate func creatNavView(){
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
    }

    
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
}

extension CommodityViewController{
    fileprivate func creatTabeleView(){
        
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        myTableView.register(CommodityTableViewCell.self, forCellReuseIdentifier: COMMODITYCELL)
        myTableView.register(ShareTableViewCell.self, forCellReuseIdentifier: SHARECELL)
        myTableView.register(CommodityDetailTableViewCell.self, forCellReuseIdentifier: DETAILCELL)
        myTableView.separatorStyle = .none
        myTableView.backgroundColor = UIColor.white
        myTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.imageDataArray.removeAllObjects()
            self.attributeArray.removeAllObjects()
            SVProgressHUD.show(withStatus: "Loading...")
            self.getData()
        })
        
        
        
        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell1 = tableView.dequeueReusableCell(withIdentifier: SHARECELL)
        let cell2 = tableView.dequeueReusableCell(withIdentifier: COMMODITYCELL)
        let cell3 = tableView.dequeueReusableCell(withIdentifier: DETAILCELL)
        cell1?.selectionStyle = .none
        cell2?.selectionStyle = .none
        cell3?.selectionStyle = .none
        if indexPath.row == 0 {
            (cell1 as? ShareTableViewCell)?.priceLabel.text = self.dataDic["products_price"] as? String
            (cell1 as? ShareTableViewCell)?.shareBtn.addTarget(self, action: #selector(shareBtnClick), for: .touchUpInside)
            return cell1!
        }else if indexPath.row < 4 && indexPath.row > 0{
            (cell2 as? CommodityTableViewCell)?.myImgView.image = UIImage(named: self.imageArray[indexPath.row-1])
            (cell2 as? CommodityTableViewCell)?.myTitleLabel.text = self.titleArray[indexPath.row-1]
            
            return cell2!
            
        }else{
            (cell3 as? CommodityDetailTableViewCell)?.detailLabel.text = self.dataDic["products_name"] as? String
            return cell3!
        }
        
        
        
        
    }
    
//    分享按钮点击方法
    func shareBtnClick(){
        // 1.创建分享参数
//        let shareParames = NSMutableDictionary()
//        shareParames.ssdkSetupShareParams(byText: "share content", images: UIImage(named: "search_icon.png"), url: URL(string: "http://www.baidu.com"), title: "title", type: SSDKContentType.image)
//
//        
//        //2.进行分享
//        
//        ShareSDK.share(SSDKPlatformType.typeFacebook, parameters: shareParames) { (state : SSDKResponseState, nil, entity : SSDKContentEntity?, error :NSError?) in
//            
//            switch state{
//
//            case SSDKResponseState.success: print("分享成功")
//            case SSDKResponseState.fail:    print("授权失败,错误描述:\(error)")
//            case SSDKResponseState.cancel:  print("操作取消")
//                
//            default:
//                break
//            }
//            
//        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 1 {
            
            let message = String(describing: self.dataDic["products_price"]!) + "\nThe model is:" + String(describing: self.dataDic["products_description"]!) + "\n" + String(describing: self.dataDic["products_model"]!) + "\n" + String(describing: self.dataDic["products_name"]!)
            
            JCAlertView.showOneButton(withTitle: "Product Info", message: message, buttonType: .cancel, buttonTitle: "Got it.", click: {
                
            })
            
        }
        
        if indexPath.row == 2 {
            
            let reviewVC = ReviewsViewController()
            reviewVC.productID = self.idStr
            self.navigationController?.pushViewController(reviewVC, animated: true)
            
            
        }
        
        if indexPath.row == 3 {
            if UserSession.shareInstance.isLogin == false || UserSession.shareInstance.isLogin == nil{
                SVProgressHUD.showInfo(withStatus: "Please login first!")
                return
            }else{
                
                let urlStr = APIBASE + "main_page=wishlist_actions"
                let parma = ["act":"add","products_id":self.idStr,"zenid":UserSession.shareInstance.cookie!]
                
                NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject], finishedBlock: { (result, error) in
                    if result != nil{
                        
                        let number = String(describing: (result! as? NSDictionary)!["status"]!)
                        if number == "1"{
                            SVProgressHUD.showSuccess(withStatus: "Add a success!")
                        }else{
                            SVProgressHUD.showInfo(withStatus: "Add a failure!")
                        }
                        
                    }else{
                        SVProgressHUD.showError(withStatus: "add wishlist error:" + String(describing: error))
                        print("add wishlist error:" + String(describing: error))
                    }
                })
                
                
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView = UIView()
        headView.backgroundColor = UIColor.white
        let array = NSMutableArray(capacity: 0)
        
        for dic in self.imageDataArray {
            let imageStr = (dic as! NSDictionary)["image_base"]as?String
//            let imageStr = dic["image_base"]as?String
            array.add(imageStr!)
        }
//        if array.count != 0 {
//            self.mainScrollView = SSCycleScrollView.init(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH), animationDuration: 3, inputImageUrls: (array as? [String])!)
//            self.mainScrollView?.showsHorizontalScrollIndicator = false
//            self.mainScrollView?.tapBlock = {index in
//                print("tapped page\(index)")
//            }
//            headView.addSubview(mainScrollView!)
//        }else{
//            let imageView = UIImageView()
//            imageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)
//            imageView.contentMode = .ScaleAspectFit
//            imageView.clipsToBounds = true
//            imageView.sd_setImageWithURL(NSURL(string: self.productImgView))
//            headView.addSubview(imageView)
//        }
        
        
        if array.count != 0{
            let dataSource = self.dataDic["addtional_images"] as! [[String : String]]
//            print(dataSource)
            sliderView = FYSliderView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH),option:self)
            sliderView.delegate = self
            self.sliderView?.imageObjectGroup = dataSource.map({ dic in
                return FYImageObject(url: dic["image_base"], title: "")
            })
            
            
            
            for dic in dataSource{
                let items = KNPhotoItems()
                items.url = String(describing: (dic as NSDictionary)["image_large"]!)
                self.itemsArray.add(items)
                
            }
            
            
            
            headView.addSubview(sliderView)
        }else{
            let imageView = UIImageView()
            imageView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH)
            imageView.contentMode = .scaleAspectFit
            imageView.clipsToBounds = true
            imageView.sd_setImage(with: URL(string: self.productImgView))
            imageView.isUserInteractionEnabled = true
            headView.addSubview(imageView)
            
            let items = KNPhotoItems()
            items.url = self.productImgView
            self.itemsArray.add(items)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(onePhotoClick))
            imageView.addGestureRecognizer(tap)
        }
        
        
        
        
        return headView
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SCREEN_WIDTH
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 4 {
            return SCREEN_HEIGHT * 0.12
        }else{
            return SCREEN_HEIGHT * 0.08
        }
    }
    
    //一张图片的时候的点击事件
    func onePhotoClick(){
        if sizeView.superview == self.view{
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(tableViewTapClick(tap:)))
            myTableView.addGestureRecognizer(tap)
            
        }else{
            let photoBrower = KNPhotoBrower()
            photoBrower.isNeedRightTopBtn = false
            photoBrower.itemsArr = self.itemsArray as [AnyObject]
            photoBrower.currentIndex = 0
            photoBrower.present()
        }
        
    }
    
}
extension CommodityViewController:FYSliderViewDelegate{
    
    
    
    
    func sliderView(didScrollToIndex index: Int) {
//        print("滚到了\(index)")
    }
    
    func sliderView(didSelectItemAtIndex index: Int) {
//        print("点击了\(index)")
        if sizeView.superview == self.view{
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(tableViewTapClick(tap:)))
            myTableView.addGestureRecognizer(tap)
            
        }else{
            let photoBrower = KNPhotoBrower()
            photoBrower.isNeedRightTopBtn = false
            photoBrower.itemsArr = self.itemsArray as [AnyObject]
            photoBrower.currentIndex = index
            photoBrower.present()
        }
        
        
        
        
        
    }
    
    
    func tableViewTapClick(tap : UITapGestureRecognizer){
        if sizeView.bounds.size.height>0 {
            UIView.animate(withDuration: 0.5, animations: {
                self.sizeView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*CGFloat(self.attributeArray.count)*0.08)
            }, completion: { (Bool) in
                self.sizeView.removeFromSuperview()
                self.myTableView.removeGestureRecognizer(tap)
            })
            
            
        }
    }
    
    
}


extension CommodityViewController{
    fileprivate func creatAddToCartView(){
        let addView = UIView()
        addView.frame = CGRect(x: 0, y: SCREEN_HEIGHT*0.92, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.08)
        addView.backgroundColor = UIColor.black
        self.view.addSubview(addView)
        
        let iconImageView = UIImageView()
        iconImageView.image = UIImage(named: "product_shopping")
        iconImageView.frame = CGRect(x: SCREEN_WIDTH*0.25, y: SCREEN_HEIGHT*0.08/2-15, width: 30, height: 30)
        addView.addSubview(iconImageView)
        
        let label = UILabel()
        label.frame = CGRect(x: SCREEN_WIDTH*0.25+60, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH*0.6, height: SCREEN_HEIGHT*0.06)
        label.textColor = UIColor.white
        label.text = "ADD TO CART"
        addView.addSubview(label)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(addViewClick))
        addView.addGestureRecognizer(tap)
        
    }
    
    
    func addViewClick(){
        
        if self.attributeArray.count == 0 {
            SVProgressHUD.showInfo(withStatus: "no size！not sell")
        }else{
            sizeView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*CGFloat(self.attributeArray.count)*0.06)
            sizeView.backgroundColor = UIColor.white
            sizeView.layer.borderWidth = 1
            sizeView.layer.borderColor = UIColor.gray.cgColor
            self.view.addSubview(sizeView)
            
            for i in 0..<self.attributeArray.count {
                let sizeStr = (self.attributeArray[i] as? NSDictionary)?["products_options_values_name"]as?String
                let priceStr = (self.attributeArray[i]as?NSDictionary)?["options_values_price"]as?String
                
                let button = UIButton(type: .custom)
                button.frame = CGRect(x: 0, y: SCREEN_HEIGHT*0.06*CGFloat(i), width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.06)
                button.setTitleColor(UIColor.black, for: UIControlState())
                button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
                button.titleLabel?.textAlignment = .left
                button .setTitle(sizeStr!+"(\(priceStr!))", for: UIControlState())
                button.addTarget(self, action: #selector(sizeButtonClick(_:)), for: .touchUpInside)
                button.tag = 100+i
                sizeView.addSubview(button)
                
            }
            
            UIView.animate(withDuration: 0.5, animations: {
                self.sizeView.frame = CGRect(x: 0, y: SCREEN_HEIGHT - SCREEN_HEIGHT*CGFloat(self.attributeArray.count)*0.06, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*CGFloat(self.attributeArray.count)*0.06)
            }) 
        }
        
        
        
    }
    
    func sizeButtonClick(_ button:UIButton){
        let index = button.tag - 100
        let sizeIdStr = (self.attributeArray[index]as?NSDictionary)?["products_options_values_id"]as?String
        let str = "id[\(self.products_options_id)]"
        let urlStr = APIBASE + "main_page=cart_actions"
        let parma = ["act":"add","products_id":self.idStr,"cart_quantity":"1",str:sizeIdStr!,"zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                SVProgressHUD.showSuccess(withStatus: "Add to cart success!")
                self.goToShoppingCart()

            }else{
                SVProgressHUD.showError(withStatus: "Add to cart error:" + String(describing: error))
                print("Add to cart error:" + String(describing: error))
            }
        }
        
    }
    
    func goToShoppingCart(){
        if sizeView.bounds.size.height>0 {
            UIView.animate(withDuration: 0.5, animations: {
                self.sizeView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*CGFloat(self.attributeArray.count)*0.08)
                }, completion: { (Bool) in
                    self.sizeView.removeFromSuperview()
                    let shopVC = ShoppingCarViewController()
                    shopVC.isCommodityVC = "yes"
                    
                    self.navigationController?.pushViewController(shopVC, animated: true)
            })
        }

        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if sizeView.bounds.size.height>0 {
            UIView.animate(withDuration: 0.5, animations: {
                self.sizeView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*CGFloat(self.attributeArray.count)*0.08)
                }, completion: { (Bool) in
                    self.sizeView.removeFromSuperview()
            })
        }
    }
}












